package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId+'_'+#dish.name+'_1'")
    public R list(Dish dish) {

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.like(dish.getName() != null, Dish::getName, dish.getName());
        lqw.eq(Dish::getStatus, 1);
        lqw.orderByDesc(Dish::getSort);
        List<Dish> dishList = dishService.list(lqw);

        List<DishDto> collect = dishList.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            LambdaQueryWrapper<DishFlavor> dishFlavorLqw = new LambdaQueryWrapper<>();
            dishFlavorLqw.in(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLqw);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(collect);
    }

    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R delete(@RequestParam List<Long> ids) {
        log.info("ids {}", ids);
        dishService.delete(ids);
        return R.success("删除成功");
    }

    //修改状态
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dishCache",allEntries = true)
    public R updateStatus(@PathVariable int status, @RequestParam List<Long> ids) {
        log.info("status {} 和 ids {} ", status, ids);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.updateStatusById(status, ids);
        return R.success("修改成功");
    }

    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R update(@RequestBody DishDto dishDto) {
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    //数据回显
    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //首页查询 使用Mapper直接查询数据
//    @GetMapping("/page")
//    public R page(int page,int pageSize,String name){
//        Page<DishDto> dishPage = new Page<>(page, pageSize);
//        dishService.pageByName(dishPage,name);
//        return R.success(dishPage);
//    }

    //使用 ==属性拷贝== 的方法实现 但是和数据库频繁交互 性能较低
//    @GetMapping("/page")
//    public R page(int page, int pageSize, String name) {
//        //分页查询查到数据
//        Page<Dish> dishPage = new Page<>(page, pageSize);
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
//        lqw.orderByDesc(Dish::getUpdateTime);
//        dishService.page(dishPage, lqw);
//        //将DishPage的相关数据拷到DishDtoPage中,除了其中的集合属性，因为DishPage中没有套餐名的值，而DishDtoPage中有该属性
//        Page<DishDto> dishDtoPage = new Page<>();
//        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
//
//        //将DishPage中的集合取出来
//        List<Dish> dishPageRecords = dishPage.getRecords();
//
//        //使用lambda表达式将数据取到新的集合中
//        List<DishDto> collect = dishPageRecords.stream().map((item) -> {
//            //根据套餐id查询套餐姓名并赋值给DishDto
//            Category category = categoryService.getById(item.getCategoryId());
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(item, dishDto);
//            dishDto.setCategoryName(category.getName());
//            return dishDto;
//        }).collect(Collectors.toList());
//        //将集合赋值给DishDtoPage中并传给前端
//        dishDtoPage.setRecords(collect);
//        return R.success(dishDtoPage);
//    }

    //优化上面的代码 减少交互的次数 去重时可以将数据保存到 ==Set集合==中 或者
    // 可以直接stream的 ==distinct()== 方法来去重可返回任意类型的集合
    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {

        //分页查询查到数据
        Page<Dish> dishPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, lqw);
        //将DishPage的相关数据拷到DishDtoPage中,除了其中的集合属性，因为DishPage中没有套餐名的值，而DishDtoPage中有该属性
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //将DishPage中的集合取出来
        List<Dish> dishPageRecords = dishPage.getRecords();

        if (dishPageRecords.size() > 0) {
            //将菜品id保存到set集合中
            List<Long> categoryIds = dishPageRecords.stream().map(Dish::getCategoryId).distinct().collect(Collectors.toList());

            //根据id查询所有的菜品集合
            List<Category> categories = categoryService.listByIds(categoryIds);

            //将集合中的id和name保存到一个map中方便使用
            Map<Long, String> categoryMap = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));

            //使用lambda表达式将数据取到新的集合中
            List<DishDto> collect = dishPageRecords.stream().map((item) -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(item, dishDto);
                dishDto.setCategoryName(categoryMap.get(item.getCategoryId()));
                return dishDto;
            }).collect(Collectors.toList());
            //将集合赋值给DishDtoPage中并传给前端
            dishDtoPage.setRecords(collect);
        }
        return R.success(dishDtoPage);
    }

    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R save(@RequestBody DishDto dishDto) {
        //log.info("前端传的数据dishDto为 {}", dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }
}
